<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>基本信息及资质</span>
            <div class="container" v-if="op == 'mycust' || op == 'must' || op == 'recust'">

              <el-button type="primary" v-if="form.id != null" size="mini" @click="updateToPublic">加入公共池
              </el-button>
              <el-button type="primary" v-if="form.id != null && op != 'must'" size="mini"
                         @click="batchUpdateToMust">加入必跟进
              </el-button>


              <el-button type="primary" size="mini" @click="handlePrevious">上一个客户</el-button>
              <el-button type="primary" size="mini" @click="handleNext">下一个客户</el-button>
            </div>
          </div>

          <el-form ref="form" :model="form" :rules="rules" label-width="auto"
                   label-position="left">
            <el-row>
              <el-col :span="6">
                <el-form-item label="客户" prop="custName">
                  <el-input v-model="form.custName" placeholder="客户名称" style="width: 78px;"/>
                  <span
                      v-show="opFrom != 'view' && opFrom != 'dianpin' && opFrom != 'withdrawn' && opFrom != 'deleting'"
                      style="margin-left: 5px;">
                    <el-input v-show="isadd" v-model="form.mobile" placeholder="手机号" style="width: 120px;"
                              :rules="[{ validator: phoneNumberValidator }]"/>

                    <el-button v-show="isEdit" type="primary" circle @click="getPhone" v-model="form.mobile"
                               size="mini" icon="el-icon-search"></el-button>
                    <el-button v-show="isEdit" type="primary" icon="el-icon-phone" circle @click="callPhone"
                               size="mini"></el-button>
                  </span>
                </el-form-item>

              </el-col>
              <el-col :span="6">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model.number="form.age" placeholder="请输入年龄"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_sex" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="婚否" prop="marriaged">
                  <el-radio-group v-model="form.marriaged" placeholder="请选择婚否" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_marriage" :key="dict.value" :label="dict.value"
                                     :value="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="公积金" prop="hasFund">
                  <el-radio-group v-model="form.hasFund" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="社保" prop="hasSocial">
                  <el-radio-group v-model="form.hasSocial" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="执照" prop="hasCompany">
                  <el-radio-group v-model="form.hasCompany" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">

                <el-form-item label="爱人知晓" prop="loverKnowed">
                  <el-radio-group v-model="form.loverKnowed" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_has" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>


            <el-row v-show="form.hasFund == 1">
              <el-col :span="6">
                <el-form-item label="公积金年份" prop="fundYears">
                  <el-input v-model="form.fundYears" placeholder="请输入公积金年份"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="公积金金额" prop="fundAmt">
                  <el-input v-model="form.fundAmt" placeholder="请输入公积金金额"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-show="form.hasSocial == 1">
              <el-col :span="6">

                <el-form-item label="社保年份" prop="socialYears">
                  <el-input v-model="form.socialYears" placeholder="请输入社保年份"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="社保金额" prop="socialAmt">
                  <el-input v-model="form.socialAmt" placeholder="请输入社保金额"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="职业" prop="hasWork">
                  <el-radio-group v-model="form.hasWork" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="房" prop="hasHouse">
                  <el-radio-group v-model="form.hasHouse" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="车" prop="hasCar">
                  <el-radio-group v-model="form.hasCar" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-show="form.hasWork == 1">
              <el-col :span="6">
                <el-form-item label="单位性质" prop="workNature">
                  <el-select v-model="form.workNature" placeholder="请选择单位性质">
                    <el-option v-for="dict in dict.type.crm_work" :key="dict.value" :label="dict.label"
                               :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发薪方式" prop="workPaytype">

                  <el-select v-model="form.workPaytype" placeholder="请选择发薪方式">
                    <el-option v-for="dict in dict.type.crm_paytype" :key="dict.value" :label="dict.label"
                               :value="dict.value"></el-option>
                  </el-select>

                </el-form-item>

              </el-col>
            </el-row>

            <el-row v-show="form.hasHouse == 1">
              <el-col :span="6">
                <el-form-item label="房屋状态" prop="houseType">
                  <el-radio-group v-model="form.houseType" size="mini">
                    <el-radio-button :label="0">全款</el-radio-button>
                    <el-radio-button :label="1">按揭</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="面积" prop="houseArea">
                  <el-input v-model="form.houseArea" placeholder="请输入面积"/>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="价值" prop="houseValue">
                  <el-input v-model="form.houseValue" placeholder="请输入价值"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-show="form.houseType == 1">
              <el-col :span="6">
                <el-form-item label="按揭多久" prop="houseTimes">
                  <el-input v-model="form.houseTimes" placeholder="请输入按揭多久"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="月供" prop="houseMonthPay">
                  <el-input v-model="form.houseMonthPay" placeholder="请输入月供"/>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="按揭银行" prop="houseBankName">
                  <el-input v-model="form.houseBankName" placeholder="请输入按揭银行"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-show="form.hasCar == 1">
              <el-col :span="6">
                <el-form-item label="车辆状态" prop="carType">
                  <el-radio-group v-model="form.carType" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_cartype" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>

              </el-col>
              <el-col :span="6">
                <el-form-item label="年限" prop="carTimeLimit">
                  <el-input v-model="form.carTimeLimit" placeholder="请输入年限"/>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="裸车价" prop="carValue">
                  <el-input v-model="form.carValue" placeholder="请输入裸车价"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-show="form.hasPolicy == 1">
              <el-col :span="6">

                <el-form-item label="投保公司" prop="policyCompany">
                  <el-input v-model="form.policyCompany" placeholder="请输入投保公司"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">

                <el-form-item label="支付方式" prop="policyPayType">
                  <el-radio-group v-model="form.policyPayType" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_policypaytype" :key="dict.value"
                                     :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="缴费次数" prop="policyPayTime">
                  <el-input v-model="form.policyPayTime" placeholder="请输入缴了几年几次"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="信用卡" prop="hasCredit">
                  <el-radio-group v-model="form.hasCredit" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="贷款总额" prop="debtAmt">
                  <el-input v-model="form.debtAmt" placeholder="请输入贷款总额"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="贷款逾期" prop="debtOverdue">
                  <el-radio-group v-model="form.debtOverdue" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="资金需求" prop="applyLimit">
                  <el-input v-model="form.applyLimit" placeholder="请输入资金需求"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-show="form.hasCredit == 1">
              <el-col :span="6">
                <el-form-item label="信用卡总额" prop="creditAmount">
                  <el-input v-model="form.creditAmount" placeholder="请输入信用卡总额"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">

                <el-form-item label="逾期情况" prop="creditOverdue">
                  <el-radio-group v-model="form.creditOverdue" size="mini">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="是否加微信" prop="addWx">
                  <el-radio-group v-model="form.addWx" size="mini" :disabled="addWxRedioDisable"
                                  @change="confirmChangeAddwx">
                    <el-radio-button label="0" key="0">未加</el-radio-button>
                    <el-radio-button label="1" key="1">已加未通过</el-radio-button>
                    <el-radio-button label="2" key="2">已加通过</el-radio-button>
                  </el-radio-group>

                </el-form-item>
              </el-col>
              <el-col :span="6">

                <el-form-item label="是否电话接通" prop="connectPhone">
                  <el-radio-group v-model="form.connectPhone" size="mini" :disabled="contactPhoneRedioDisable"
                                  @change="confirmChangeConnPhone">
                    <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                        dict.label
                      }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>


          </el-form>


          <el-tabs v-model="activeTab">
            <el-tab-pane label="客户跟踪" name="customerTracking">

              <el-form ref="form2" :model="form" :rules="rules" label-width="120px">
                <div>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="ID" prop="id">
                        {{ form.id }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="星级" prop="starLevel">
                        <el-select v-model="form.starLevel" placeholder="请选择星级" @change="setStatusByStarLevel">
                          <el-option v-for="dict in dict.type.crm_star" :key="dict.value" :label="dict.label"
                                     :value="dict.value"></el-option>
                        </el-select>
                      </el-form-item>

                    </el-col>
                    <el-col :span="6">

                      <el-form-item label="状态" prop="status">
                        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                          <el-option v-for="dict in dict.type.crm_customerStatus" :key="dict.value" :label="dict.label"
                                     :value="dict.value"></el-option>
                        </el-select>
                      </el-form-item>

                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="需求额度" prop="allocationRecords">
                        <el-select v-model="form.amountType" placeholder="请选择需求额度" style="width: 100%">
                          <el-option v-for="dict in dict.type.crm_amount" :key="dict.value" :label="dict.label"
                                     :value="dict.value"></el-option>
                        </el-select>

                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="当前跟进人" prop="userName">
                        {{ getNameByEmpId(form.userId) }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="6" v-if="false">
                      <el-form-item label="提醒时间">
                        <div class="button-group">
                          <el-button type="primary" icon="el-icon-message" @click="noticeInSomeTime(10)"
                                     size="mini">10分
                          </el-button>
                          <el-button type="primary" icon="el-icon-message" @click="noticeInSomeTime(30)"
                                     size="mini">30分
                          </el-button>
                          <el-button type="primary" icon="el-icon-message" @click="noticeInSomeTime(60)"
                                     size="mini">60分
                          </el-button>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="提醒时间" prop="nextTime">
                        <div class="button-group">
                          <div class="block">
                            <el-date-picker
                                v-model="nextTime"
                                format="yyyy-MM-dd HH:mm:ss"
                                type="datetime"
                                placeholder="选择提醒日期时间"
                                align="right"
                                :picker-options="pickerOptions">
                            </el-date-picker>
                          </div>
                          <el-button type="primary" size="mini" @click="noticeInSomeTimeDiy">设置提醒</el-button>
                        </div>
                      </el-form-item>

                    </el-col>
                  </el-row>
                  <el-row>

                    <el-col :span="6">
                      <el-form-item label="预审批额度" prop="preAuditLimit">
                        <el-input v-model="form.preAuditLimit" placeholder="请输入预审批额度"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="预审批渠道" prop="preAuditChannel">
                        <el-input v-model="form.preAuditChannel" placeholder="请输入预审批渠道"/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="本地户籍" prop="localPersonFlag">
                        <el-radio-group v-model="form.localPersonFlag" size="mini">
                          <el-radio-button v-for="dict in dict.type.crm_has" :key="dict.value" :label="dict.value">{{
                              dict.label
                            }}
                          </el-radio-button>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="本地房产" prop="hasLocalHouse1">
                        <el-radio-group v-model="form.hasLocalHouse" size="mini">
                          <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                              dict.label
                            }}
                          </el-radio-button>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="本地号段" prop="localPhoneFlag">
                        <el-radio-group v-model="form.localPhoneFlag" size="mini">
                          <el-radio-button v-for="dict in dict.type.crm_yesno" :key="dict.value" :label="dict.value">{{
                              dict.label
                            }}
                          </el-radio-button>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                    </el-col>
                  </el-row>
                  <el-divider></el-divider>

                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="已点评" prop="dpRemark">
                        <el-card class="box-card" :body-style="{ padding: '6px 10px' }" style="min-height: 60px;">
                          <div v-for="(item, index) in dpRemarkResult" :key="index" class="text item">
                            {{ index + 1 }},{{ item.createTime }}{{ item.remark }}
                          </div>
                        </el-card>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="已备注" prop="remark">
                        <el-card class="box-card" style="min-height: 60px;" :body-style="{ padding: '6px 10px' }">
                          <div v-for="(item, index) in custCommentlist" :key="index" class="text item">
                            {{ index + 1 }},{{ item.createTime }}：{{ item.remark }}—{{ item.empName }}{{
                              item.nickName
                            }}&nbsp;<el-link v-show="company_leader == 1" type="primary"
                                             @click="deleteCustComment(item.id)">删除
                          </el-link>
                          </div>
                        </el-card>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col v-show="is_bz" :span="24">
                      <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入备注内容"
                                  v-model="remark">
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row v-show="is_dp">
                    <el-col :span="24">
                      <el-form-item label="点评" prop="dpRemark">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入点评内容"
                                  v-model="dpRemark">
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row v-show="opFrom != 'view' && opFrom != 'withdrawn' && opFrom != 'deleting'">
                    <el-col :span="24" align="center">
                      <el-form-item>
                        <el-button type="primary" size="mini" @click="submitForm">保存</el-button>
                        <el-button type="danger" size="mini" @click="cancel">关闭</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row v-show="opFrom == 'deleting'">
                    <el-col :span="24" align="center">
                      <el-button type="primary" size="mini" @click="updateToDelete">同意加入垃圾库</el-button>
                      <el-button type="danger" size="mini" @click="updateToPublic">打回公共池</el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="分配记录" name="resetPwd">

              <el-timeline>
                <el-timeline-item v-for="(activity, index) in distributeRemarkResult" :key="index" :icon="activity.icon"
                                  :type="activity.type" :color="activity.color" :size="activity.size"
                                  :timestamp="activity.timestamp">
                  {{ activity.content }}
                </el-timeline-item>
              </el-timeline>
              <el-empty description="暂无分配记录" v-show="distributeRemarkResult.length < 1"></el-empty>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getCustinfo,
  addCustinfo,
  updateCustinfo,
  decryptMobile,
  deletingCustPass,
  batchUpdateToPublic,
  batchUpdateToMust,
  getMyCustlist,
  getMyCustInfo,
  callPhone

} from "@/api/crmsys/custinfo/custinfo";
import {
  addNotice
} from "@/api/crmsys/custinfo/notice";

import {listRecord, delRecord} from "@/api/crmsys/record";
import {compile} from "vue-template-compiler";

export default {
  name: "custinfoedit",
  props: {
    id: {
      type: String,
      required: true
    }
  },
  dicts: [
    "crm_yesno",
    "crm_sex",
    "crm_has",
    "crm_star",
    "crm_type",
    "crm_paytype",
    "crm_amount",
    "crm_customerStatus",
    "crm_marriage",
    "crm_work",
    "crm_roleCategory",
    "crm_cartype",
    "crm_policypaytype"
  ],
  data() {
    return {
      // 表单参数
      form: {},
      is_dp: false,
      is_bz: false,
      isadd: false,
      isEdit: false,
      opFrom: null,
      oldStarLevel: null,
      oldStatus: null,
      op: null,
      queryOldParams: null,
      phone: null,
      addWxRedioDisable: false,
      contactPhoneRedioDisable: false,
      oldAddWx: null,
      // 表单校验
      rules: {
        custName: [{required: true, message: '请输入客户名称'}],
        addWx: [{required: true, message: '请选择是否加微信'}],
        connectPhone: [{required: true, message: '请选择是否接通电话'}],
        mobile: [{
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }],
        applyLimit: [{required: true, message: '请输入资金需求'},
          {pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],
        age: [{type: 'number', message: '年龄必须为数字值'}],
        fundAmt: [{pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],
        socialAmt: [{pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],
        workSalary: [{pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],
        carValue: [{pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],
        houseValue: [{pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],
        debtAmt: [{pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],
        creditAmount: [{pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '金额格式不正确', trigger: ['change', 'blur']}],


      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()//选当前时间之前的时间
        },
        shortcuts: [{
          text: '10分钟后',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 600 * 1000);
            picker.$emit('pick', date);
          }
        }, {
          text: '30分钟后',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 1800 * 1000);
            picker.$emit('pick', date);
          }
        }, {
          text: '60分钟后',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000);
            picker.$emit('pick', date);
          }
        }, {
          text: '120分钟后',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 2);
            picker.$emit('pick', date);
          }
        }, {
          text: '明天此时',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
            picker.$emit('pick', date);
          }
        }]
      },
      activeTab: "customerTracking",
      showPhoneMessage: "查看手机号",
      custCommentlist: [],
      dpRemark: "",
      noticeTime: 0,
      distributeRemarkResult: [],
      dpRemarkResult: "",
      remark: "",
      company_leader: "",
      nextTime: ""
    };
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getCustinfo();
    this.op = this.$route.query.custOpType;
    console.log(this.$store.state.tagsView.visitedViews);


  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  // methods方法
  methods: {
    confirmChangeAddwx() {
      console.log(this.form.addWx);
      if (this.form.addWx == 2) {
        this.$confirm('确定此选项保存后将无法修改, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '已确认'
          });
          this.addWxRedioDisable = true;

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
          this.form.addWx = this.oldAddWx;
        });
      } else {
        this.oldAddWx = this.form.addWx;
      }

    },
    confirmChangeConnPhone() {
      console.log(this.form.connectPhone);
      if (this.form.connectPhone == 1) {
        this.$confirm('确定此选项保存后将无法修改, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '已确认'
          });

          this.contactPhoneRedioDisable = true;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
          this.form.connectPhone = 0;
        });
      }
    },
    // 取消按钮
    cancel() {
      this.gotoList();
    },
    gotoList() {
      //跳转到List页面
      const obj = {
        path: this.$route.query.routePath,
        query: {
          t: Date.now(),
          queryParams: this.$route.query.queryParams,
          pageNum: this.$route.query.pageNum,
          custOpType: this.$route.query.custOpType
        }
      };
      this.$tab.closeOpenPage(obj);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isadd == true) {
            if (this.form.mobile == "" || this.form.mobile == null) {
              this.$modal.msgWarning("请输入手机号");
              return;
            } else {
              const regExp = /^((\+86)|(86))?\d{11}$/; // 手机号正则表达式
              if (!regExp.test(this.form.mobile)) {
                this.$modal.msgWarning("请输入正确的手机号");
                return;
              }
            }
          }
          if (this.is_dp == true && this.dpRemark == "") {
            this.$modal.msgWarning("请输入点评信息");
            return;
          }
          //如果星级调整了  也可以保存
          if (this.is_bz == true && this.remark == "" && this.form.starLevel == this.oldStarLevel) {
            this.$modal.msgWarning("请输入备注信息或变更星级信息");
            return;
          }

          if (this.dpRemark != "") {
            //点评备注
            this.form.params = typeof (this.form.params) === 'object' && this.form.params !== null && !Array.isArray(this.form.params) ? this.form.params : {};
            this.form.params.dpRemarkNew = this.dpRemark;
          }
          if (this.remark != "") {
            //备注
            this.form.params = typeof (this.form.params) === 'object' && this.form.params !== null && !Array.isArray(this.form.params) ? this.form.params : {};
            this.form.params.remarkNew = this.remark;
          }
          if (this.form.id != null) {
            updateCustinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              // this.gotoList();
              this.getCustinfo();
              this.remark = null;
              this.dpRemark = null;
            });
          } else {
            addCustinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.gotoList();
            });
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        custName: null,
        mobile: null,
        age: null,
        sex: null,
        city: null,
        household: null,
        officeTel: null,
        marriaged: null,
        hasHouse: null,
        houseType: null,
        houseArea: null,
        houseValue: null,
        houseTimes: null,
        houseMonthPay: null,
        houseBankName: null,
        hasCar: null,
        carType: null,
        carTimeLimit: null,
        carValue: null,
        carTimes: null,
        carMonthPay: null,
        carBankName: null,
        hasCredit: null,
        creditAmount: null,
        creditOverdue: null,
        hasPolicy: null,
        policyCompany: null,
        policyPayType: null,
        policyPayTime: null,
        hasSocial: null,
        socialYears: null,
        socialAmt: null,
        hasFund: null,
        fundYears: null,
        fundAmt: null,
        hasWork: null,
        workNature: null,
        workSalary: null,
        workPaytype: null,
        hasCompany: null,
        hasTax: null,
        debtAmt: null,
        debtOverdue: null,
        loverKnowed: null,
        zhimaScore: null,
        wedebtLimit: null,
        applyLimit: null,
        applyTime: null,
        updateTime: null,
        distributeTime: null,
        oldDistributeTime: null,
        reDistributeTime: null,
        reDistributeStatus: null,
        mediaSource: null,
        channelSource: null,
        orgId: null,
        empId: null,
        starLevel: null,
        status: null,
        preAuditLimit: null,
        preAuditChannel: null,
        remark: null,
        dpRemark: null,
        wishRemark: null,
        distributeRemark: null,
        hasRemind: null,
        lastUpdateBy: null,
        localPersonFlag: null,
        localPhoneFlag: null,
        candoFlag: null,
        oldEmpId: null,
        qrcodeid: null,
        isDelete: null,
        urlTrack: null,
        channelDesc: null,
        channelPsource: null,
        education: null,
        amountType: null,
        lastRemarkTime: null,
        repeatFlag: null,
        lockFlag: null,
        lockTime: null,
        hasLocalHouse: null,
        distributeId: null,
        passflag: null,
        md5val: null,
        encval: null,
        addWx: null,
        connectPhone: null
      };
      this.resetForm("form");
    },
    deleteCustComment(id) {
      this.$confirm('确定删除备注？?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRecord(id).then(response => {
          this.$message({
            type: 'success',
            message: response.msg
          });
          // 根据 ID 删除指定对象
          this.custCommentlist = this.custCommentlist.filter(item => item.id !== id);
        }).catch(e => {
              console.log(e.message);
            }
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    },
    /** 设置提醒时间 */
    noticeInSomeTime(addTime) {
      debugger;
      var date = new Date();
      var min = date.getMinutes();
      date.setMinutes(min + addTime);

      let prams = {
        noticeContent: "您的客户" + this.form.custName + "需要跟进",
        noticeTime: this.timeStamp2String(date.getTime()),
        noticeCustId: this.form.id,
        noticeType: 1,
        noticeTitle: "提醒",
        noticeEmpNo: this.$store.state.user.name

      };


      addNotice(prams).then((response) => {
        if (response.code == 200) {
          this.$message({
            message: "将会在" + addTime + "分钟后，将会进行提醒",
            type: 'success'
          });
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    checkTimeAfterTenMinutes(selectedTime) {
      // 获取当前时间
      const now = new Date();
      // 计算当前时间十分钟后的时间
      const tenMinutesLater = new Date(now.getTime() + 60 * 1000);
      // 将选择的时间转换为Date对象
      const selectedDate = new Date(selectedTime);
      // 判断选择的时间是否大于1分钟后的时间
      return selectedDate > tenMinutesLater;
    },
    /** 自定义提醒设置提醒时间 */
    noticeInSomeTimeDiy() {
      var addTime = this.checkTimeAfterTenMinutes(this.nextTime);
      if (!addTime) {
        this.$message.error("请选择大于当前时间且大于1分钟的时间");
        return;
      }
      //Wed Sep 03 2025 18:40:40 GMT+0800 (中国标准时间) 改成年月日时分秒
      var date = new Date(this.nextTime);
      var getnoticeTime = this.timeStamp2String(date.getTime());

      let prams = {
        noticeContent: "您的客户" + this.form.custName + "需要跟进",
        noticeTime: getnoticeTime,
        noticeCustId: this.form.id,
        noticeType: 1,
        noticeTitle: "提醒",
        noticeEmpNo: this.$store.state.user.name

      };

      addNotice(prams).then((response) => {
        if (response.code == 200) {
          this.$message({
            message: "将会在：" + getnoticeTime + " 进行提醒",
            type: 'success'
          });
          this.nextTime = null;
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    timeStamp2String(time) {
      var datetime = new Date();
      datetime.setTime(time);
      var year = datetime.getFullYear();
      var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
      var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
      var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
      var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
      var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
      return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    },
    getCustinfo() {
      const id = this.$route.query.id;
      this.opFrom = this.$route.query.opFrom;
      this.phone = null;
      if (this.opFrom == 'dianpin') {
        this.is_dp = true;
      } else {
        this.is_bz = true;
      }


      if (id != null && id != "") {
        getCustinfo(id).then(response => {
          this.form = response.data;
          //保存星级信息，做后续判断
          this.oldStarLevel = this.form.starLevel;
          this.oldStatus = this.form.status;
          this.getDistributeRemark();
          this.getCustCommentlist();
          this.setStatusByStarLevel();
          this.oldAddWx = this.form.addWx;
          console.log(this.form.addWx);
          if (this.form.addWx == 2) {
            this.addWxRedioDisable = true;
          }
          if (this.form.connectPhone == 1) {
            this.contactPhoneRedioDisable = true;
          }
        });
        this.isEdit = true;
      } else {
        this.isadd = true;
      }
    },
    getPhone() {
      if (this.showPhoneMessage == "查看手机号") {
        if (this.phone != null) {
          this.$alert(
              this.phone
          );
        } else {
          decryptMobile({
            "md5val": this.form.md5val,
            "id": this.form.id,
            "encval": this.form.encval,
            "mobile": this.form.mobile
          }).then(response => {
            this.showPhoneMessage = response.msg;
            this.phone = response.msg;

            this.$alert(
                this.phone
            );
          });
        }
      } else {
        this.showPhoneMessage = "查看手机号"
      }
    },
    copyToClipboard(text) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success("手机号已复制到剪贴板");
        }).catch(err => {
          console.error('复制失败:', err);
          this.$message.error("复制手机号失败");
        });
      } else {
        // Fallback for older browsers
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        this.$message.success("手机号已复制到剪贴板");
      }
    },
    //获取已备注信息
    getCustCommentlist() {
      let custId = {"custId": this.form.id}
      listRecord(custId).then(response => {
        this.custCommentlist = response.rows;
        this.custCommentlist.sort(function (a, b) {
          return new Date(b["create_time"]) - new Date(a["create_time"]); // 降序排列
        });
      });
    },
    //获取记录备注格式化显示
    getDistributeRemark() {
      this.distributeRemarkResult = [];
      this.dpRemarkResult = [];
      if (this.form.distributeRemark != null && this.form.distributeRemark !== "") {
        //获取分配记录备注格式化显示
        let disArr = this.form.distributeRemark.split("<br>");
        for (let index = 0; index < disArr.length; index++) {
          const element = disArr[index];
          let jsonobj = {
            "timestamp": element.substring(0, 19),
            size: 'large',
            type: 'primary',
            "content": element.substring(19)
          }
          //判断19位的time是否是时间类型，如果是就不做操作，否则只保留年月日

          //后台distributeRemark这个字段，需要把时分秒给加上
          // 包括功能 加入公共池  加入垃圾库  回收原始分配到分公司负责人名下  回收至待分配  新数据分配  公共池/团队客户/离职客户数据分配  加入我的客户 获取客户加入我的再分配客户池
          // 新增客户信息 修改客户信息
          this.distributeRemarkResult.push(jsonobj);
        }

      }

      if (this.form.dpRemark != null && this.form.dpRemark !== "") {
        //获取分配记录备注格式化显示
        let disArr = this.form.dpRemark.split("<br>");
        for (let index = 0; index < disArr.length; index++) {
          const element = disArr[index];
          let jsonobj = {"createTime": element.substring(0, 19), "remark": element.substring(19)}
          this.dpRemarkResult.push(jsonobj);
        }

      }
    }, phoneNumberValidator(rule, value, callback) {
      if (value === '') {
        callback(); // 如果没有输入值，直接通过校验
      } else {
        const regExp = /^((\+86)|(86))?\d{11}$/; // 手机号正则表达式
        if (!regExp.test(value)) {
          callback('请输入正确的手机号'); // 若不符合手机号格式，调用callback传递错误消息
        } else {
          callback(); // 符合手机号格式，通过校验
        }
      }
    },
    //同意加入垃圾库
    updateToDelete() {
      let custId = this.form.id;

      this.$confirm('确认同意该客户加入垃圾库？?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletingCustPass(custId).then(response => {
          this.$message({
            type: 'success',
            message: response.msg
          });
        }).catch(e => {
              console.log(e.message);
            }
        );
      }).catch(() => {
      });


    },
    //打回公共池
    updateToPublic() {
      let custId = this.form.id;
      this.$confirm('确认将该客户加入公共池?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchUpdateToPublic(custId).then(response => {
          this.$message({
            type: 'success',
            message: response.msg
          });
          this.handleNext();
        }).catch(e => {
              console.log(e.message);
            }
        );
      }).catch(() => {
      });

    },
    batchUpdateToMust() {
      let custId = this.form.id;
      this.$confirm('确认将所选客户加入必跟进池?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchUpdateToMust(custId).then(response => {
          this.$message({
            type: 'success',
            message: response.msg
          });
          this.handleNext();
        }).catch(e => {
              console.log(e.message);
            }
        );
      }).catch(() => {
      });

    },
    //上一个客户
    handlePrevious() {
      this.$modal.loading("正在加载，请稍候...");
      //当前客户id
      let custId = this.form.id
      //获取参数
      let queryParams = JSON.parse(JSON.stringify(JSON.parse(this.$route.query.queryParams)));

      queryParams.params.isPrevious = 1;
      queryParams.params.isNext = null;
      queryParams.params.custId = custId;
      getMyCustInfo(queryParams).then((response) => {
        if (response.code != 200 || response.data == null) {
          this.$message.error("无上一个客户");
          this.$modal.closeLoading();
          return;
        }
        // this.$route.query.id = response.data.id;
        // this.form = response.data;
        // this.getDistributeRemark();
        // this.getCustCommentlist();
        // this.phone=null;
        // this.showPhoneMessage = "查看手机号"
        this.$modal.closeLoading();

        this.gotoNextCust(response.data.custName, response.data.id)
      });

    },
    //下一个客户
    handleNext() {
      this.$modal.loading("正在加载，请稍候...");
      //当前客户id
      let custId = this.form.id
      //获取参数
      let queryParams = JSON.parse(JSON.stringify(JSON.parse(this.$route.query.queryParams)));

      queryParams.params.isPrevious = null;
      queryParams.params.isNext = 1;
      queryParams.params.custId = custId;
      this.phone = null;
      queryParams.pageSize = 1;
      getMyCustInfo(queryParams).then((response) => {
        if (response.code != 200 || response.data == null) {
          this.$message.error("无下一个客户");
          this.$modal.closeLoading();
          return;
        }
        this.$modal.closeLoading();
        this.gotoNextCust(response.data.custName, response.data.id)
        // this.$route.query.id = response.data.id;
        // this.form = response.data;
        // this.getDistributeRemark();
        // this.getCustCommentlist();
        // this.showPhoneMessage = "查看手机号"
        // this.phone=null;
      });
    },
    gotoNextCust(custName, id) {
      const params = {
        id: id,
        queryParams: this.$route.query.queryParams,
        pageNum: this.$route.query.pageNum,
        custOpType: this.$route.query.custOpType
      };
      this.$tab.openPage(`客户[${custName}]`, `/crmsys/custedit/info/${id}`, params);
    },
    callPhone() {
      this.$modal.loading("正在拨打，请稍后...");
      //外呼打电话
      callPhone(this.form.id).then(response => {
        if (response.code == 200 && response.data.code == 0) {
          this.$modal.msgSuccess("已成功拨打");
        } else {
          this.$modal.msgError(response.data.msg);
        }
      });
      this.$modal.closeLoading();
    },
    setStatusByStarLevel() {

      if (this.oldStatus == '2' || this.oldStatus == '4' || this.oldStatus == '5' || this.oldStatus == '11') {
        return;
      }
      if (!this.form.starLevel || this.form.starLevel == '0') {
        this.form.status = '1';
      } else if (this.form.starLevel == '9') {
        this.form.status = '7';
      } else if (this.form.starLevel == '1') {
        this.form.status = '6';
      } else {
        this.form.status = '3';
      }

    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
.button-group {
  white-space: nowrap;
  /* 防止换行 */
  display: flex;
}

.button-group button {
  padding: 6px;
}

.clearfix {
  display: flex;
}

.container {
  margin-left: auto;
}

.ui-record {
  border: 1px solid #e6e6e6;
  padding: 6px 10px;
  line-height: 1.6;
  min-height: 86px;
  width: 500px
}
</style>
